const BASE_URL = 'http://localhost:8080/api';

function request(options) {
    const token = uni.getStorageSync('token');

    return new Promise((resolve, reject) => {
        uni.request({
            url: BASE_URL + options.url,
            method: options.method || 'GET',
            data: options.data || {},
            header: {
                'Content-Type': options.contentType || 'application/json',
                'Authorization': token ? `Bearer ${token}` : ''
            },
            success: (res) => {
                const { data, statusCode } = res;

                if (statusCode === 200) {
                    resolve(data);
                } else if (statusCode === 401) {
                    // Token失效，跳转到登录页
                    uni.reLaunch({
                        url: '/pages/home/login'
                    });
                    reject(new Error('未授权'));
                } else {
                    reject(new Error(data.message || '请求失败'));
                }
            },
            fail: (err) => {
                uni.showToast({
                    title: '网络请求失败',
                    icon: 'none'
                });
                reject(err);
            }
        });
    });
}

export default {
    get(url, data) {
        return request({ url, data });
    },
    post(url, data, contentType) {
        return request({ 
            url, 
            data, 
            method: 'POST',
            contentType
        });
    },
    put(url, data) {
        return request({ 
            url, 
            data, 
            method: 'PUT' 
        });
    },
    delete(url, data) {
        return request({ 
            url, 
            data, 
            method: 'DELETE' 
        });
    },
    upload(url, filePath) {
        return new Promise((resolve, reject) => {
            const token = uni.getStorageSync('token');

            uni.uploadFile({
                url: BASE_URL + url,
                filePath,
                name: 'file',
                header: {
                    'Authorization': token ? `Bearer ${token}` : ''
                },
                success: (res) => {
                    const data = JSON.parse(res.data);
                    if (res.statusCode === 200) {
                        resolve(data);
                    } else {
                        reject(new Error(data.message || '上传失败'));
                    }
                },
                fail: (err) => {
                    uni.showToast({
                        title: '上传失败',
                        icon: 'none'
                    });
                    reject(err);
                }
            });
        });
    }
}; 